package igc

import (
	"fmt"
	"image"
	"image/draw"
	"mime/multipart"
	"os"
	"path/filepath"
	"strings"

	ico "github.com/biessek/golang-ico"
	"github.com/nfnt/resize"
	"golang.org/x/image/bmp"

	_ "image/jpeg" // 注册JPEG解码器
	_ "image/png"  // 注册PNG解码器
)

// 图片格式转换
func Convert2Image(sourceName string, outputName string, outputType string, r ...image.Rectangle) error {
	inputFile, err := os.Open(sourceName)
	if err != nil {
		return err
	}
	defer inputFile.Close()

	// 解码图片
	img, _, err := image.Decode(inputFile)
	if err != nil {
		return err
	}
	var newRec image.Rectangle
	if len(r) > 0 {
		newRec = r[0]
		img = resize.Resize(uint(newRec.Dx()), uint(newRec.Dy()), img, resize.NearestNeighbor)

	} else {
		newRec = img.Bounds()
	}

	newImage := image.NewRGBA(img.Bounds())
	// 绘制源图像到新图像上，这里可能需要调整srcRect和dstRect以进行缩放或裁剪
	draw.Draw(newImage, newImage.Bounds(), img, image.Point{0, 0}, draw.Src)

	switch strings.ToLower(outputType) {
	case "bmp":
		outputFile, err := os.Create(ChangeFileExtension(outputName, "bmp"))
		if err != nil {
			return err
		}
		defer outputFile.Close()

		// 编码BMP图片到文件
		err = bmp.Encode(outputFile, newImage)
		if err != nil {
			return err
		}
	case "ico":
		outputFile, err := os.Create(ChangeFileExtension(outputName, "ico"))
		if err != nil {
			return err
		}
		defer outputFile.Close()
		// 编码ico
		err = ico.Encode(outputFile, newImage)
		if err != nil {
			return err
		}
	default:
		return fmt.Errorf("格式错误")
	}

	return nil
}

func Convert2ImageByFile(sourceFile multipart.File, outputName string, outputType string, r ...image.Rectangle) error {
	inputFile := sourceFile

	// 解码图片
	img, _, err := image.Decode(inputFile)
	if err != nil {
		return err
	}
	var newRec image.Rectangle
	if len(r) > 0 {
		newRec = r[0]
		img = resize.Resize(uint(newRec.Dx()), uint(newRec.Dy()), img, resize.NearestNeighbor)

	} else {
		newRec = img.Bounds()
	}

	newImage := image.NewRGBA(img.Bounds())
	// 绘制源图像到新图像上，这里可能需要调整srcRect和dstRect以进行缩放或裁剪
	draw.Draw(newImage, newImage.Bounds(), img, image.Point{0, 0}, draw.Src)

	switch strings.ToLower(outputType) {
	case "bmp":
		outputFile, err := os.Create(ChangeFileExtension(outputName, "bmp"))
		if err != nil {
			return err
		}
		defer outputFile.Close()

		// 编码BMP图片到文件
		err = bmp.Encode(outputFile, newImage)
		if err != nil {
			return err
		}
	case "ico":
		outputFile, err := os.Create(ChangeFileExtension(outputName, "ico"))
		if err != nil {
			return err
		}
		defer outputFile.Close()
		// 编码ico
		err = ico.Encode(outputFile, newImage)
		if err != nil {
			return err
		}
	default:
		return fmt.Errorf("格式错误")
	}

	return nil
}

// 修改文件名的后缀
func ChangeFileExtension(filename string, newExtension string) string {
	// 检查文件名是否有后缀
	if !strings.HasPrefix(newExtension, ".") {
		newExtension = "." + newExtension
	}
	if !strings.HasSuffix(filename, newExtension) {
		return strings.TrimSuffix(filename, filepath.Ext(filename)) + newExtension
	}
	return filename
}
